/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 30.07.2005
 *
 *************************************************/
package fightplan.ui;

/*
 * IntegerEditor is a 1.4 class used by TableFTFEditDemo.java.
 */

import java.awt.Color;
import java.awt.Component;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JFormattedTextField;
import javax.swing.JTable;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class IntegerCellEditor extends DefaultCellEditor {
	JFormattedTextField ftf;

	public IntegerCellEditor() {
		super(new JFormattedTextField());
		ftf = (JFormattedTextField) getComponent();
		ftf.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		ftf.setHorizontalAlignment(JTextField.RIGHT);
	}

	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		JFormattedTextField ftf = (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected,
				row, column);
		// if (!(value instanceof Integer && ((Integer)value).intValue() == 0))
		// {
		ftf.setValue(value);
		// }
		// else {
		// ftf.setValue("");
		// }
		return ftf;
	}

	public Object getCellEditorValue() {
		JFormattedTextField ftf = (JFormattedTextField) getComponent();
		Object o = ftf.getValue();
		if (o instanceof Integer) {
			return o;
		} else if (o instanceof Number) {
			return new Integer(((Number) o).intValue());
		} else if (o instanceof String) {
			try {
				return Integer.parseInt((String) o);
			} catch (Exception x) {
				// do nothing, will return null
			}
		}
		return new Integer(0);
	}

	public boolean stopCellEditing() {
		JFormattedTextField ftf = (JFormattedTextField) getComponent();
		try {
			ftf.commitEdit();
		} catch (java.text.ParseException exc) {
		}
		return super.stopCellEditing();
	}

}
